package com.byedu.util;

import com.fasterxml.jackson.annotation.ObjectIdGenerators;

import java.util.Date;
import java.util.UUID;

/**
 * 生成主键的工具类
 * Created by jason on 2017/5/21.
 */
public class IDGeneratorUtil {

    /**
     * 使用UUID生成主键
     * @return
     */
    public static String generateKeyByUUID () {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 形成key
     * @param date
     * @param pattern
     * @param appendedStr
     * @param parityBitLenth
     * @return
     */
    public static String generateKey(Date date, String pattern,String appendedStr, int parityBitLenth ) {
        String dateStr = CommonDateUtil.formatDateToString(date, pattern);
        return generateKey(dateStr, appendedStr, parityBitLenth);
    }

    /**
     *生成Key
     * @param majorStr1     主字符串
     * @param appendedStr   需要拼接的字符串。即将其处理成符合规则的字符串之后，与主字符串拼接形成Key
     * @param parityBitLenth 校验位的长度
     * @return
     */
    public static String generateKey(String majorStr1, String appendedStr, int parityBitLenth) {
        int srcLength = appendedStr.length();
        if (srcLength < parityBitLenth) {
            String filledStr = getVarchar(srcLength, parityBitLenth, "0");
            appendedStr = filledStr + appendedStr;
        }

        return majorStr1 + appendedStr;
    }

    /**
     * 获取自动填充的字符串
     * @param srcLenth
     * @param fiexedLength
     * @param filledStr
     * @return
     */
    public static String getVarchar(int srcLenth, int fiexedLength, String filledStr) {
        StringBuilder sb = new StringBuilder();
        int diff = srcLenth - fiexedLength;
        while(diff < 0) {
            sb.append(filledStr);
            diff++;
        }

        return sb.toString();
    }
}
